<template>
    <el-dialog class="ui-inout-dlg" top="5vh" :close-on-press-escape="false" :close-on-click-modal="false" v-model="dialogVisible" :title="dialogTitle" ref="dialog" @opened="init" :beforeClose="beforeClose" @closed="finalThings">
        <div class="co-toolbar box-row">
            <el-radio-group v-model="data.calc_mode">
                <el-radio :label="0">按件</el-radio>
                <el-radio :label="1">按个</el-radio>
            </el-radio-group>
            <span style="flex:1"></span>
            <el-form-item label="条件:" size="default" >
                <el-input class="co-search-input" placeholder="请输入商品名称或条码" v-model="params.code" clearable></el-input>
            </el-form-item>
            <el-button type="primary" @click="onSearch">查找</el-button>
        </div>
        <el-form :model="data" ref="elForm" @submit.prevent="onSure" label-width="5.5rem">
            <el-table :data="filteredData" :height="'60vh'">
                <el-table-column prop="name" label="商品名">
                    <template v-slot:default="scope">
                        <el-icon size="18" @click="onRemoveItem(scope.row, $index)" style="cursor:pointer"><Delete /></el-icon>
                        <span style="vertical-align: text-bottom; padding-left:.25rem">{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pack_size" label="每件数量" :width="80" v-if="data.calc_mode==0">
                    <template #default="scope">
                        {{ scope.row.pack_size }}个/件
                    </template>
                </el-table-column>
                <el-table-column prop="store_num" label="当前数目" :width="80"></el-table-column>
                <el-table-column prop="pack_price" :width="120" align="center">
                    <template #header>
                        <template v-if="data.calc_mode==0">单件价格</template>
                        <template v-else>单个价格</template>
                    </template>
                    <template v-slot:default="scope">
                        <template v-if="data.calc_mode==0">
                            <el-input-number class="op-num-ipt" size="default" :min="0" :controls="false" :precision="2" :step="0.01" v-model="scope.row.pack_price"></el-input-number>
                        </template>
                        <template v-else>
                            <el-input-number  class="op-num-ipt" size="default" :min="0" :controls="false" :precision="2" :step="0.01" v-model="scope.row.piece_price"></el-input-number>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="op_num" :width="120" align="center">
                    <template #header>
                        <template v-if="isIn">进货数量</template>
                        <template v-else>出货数量</template>
                    </template>
                    <template v-slot:default="scope">
                        <el-input-number  class="op-num-ipt" size="default" :min="0" :max="9999" v-model="scope.row.op_num" :step="1"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column :width="100" align="center">
                    <template #header>
                        <template v-if="isIn">进货数量</template>
                        <template v-else>出货数量</template>
                    </template>
                    <template v-slot:default="scope">
                        <span v-if="data.calc_mode==0">{{ scope.row.op_num * scope.row.pack_size }}个</span>
                        <span v-else>{{ scope.row.op_num }}个</span>
                    </template> 
                </el-table-column>
            </el-table>
            <div class="co-toolbar box-row">
                <span class="price-label">总金额: {{ data.amount }}  </span>
                    <el-link type="primary" :disabled="data.settle_mode == 0" @click="data.realpay = data.amount">填入</el-link>
                <el-form-item size="default" prop="realpay" :rules="rules.realpay">
                    <template #label>
                        <template v-if="isIn">实付:</template>
                        <template v-else>实收:</template>
                    </template>
                    <el-input-number :disabled="data.settle_mode==0" v-model="data.realpay" :min="0" :controls="false" :precision="2" :step="0.01"><template #append>元</template></el-input-number>
                </el-form-item>
                <span class="flex"></span>
                <el-radio-group v-model="data.settle_mode" @change="data.realpay = null">
                    <el-radio :label="0">挂账(不计入本班收支)</el-radio>
                    <el-radio :label="2">现金</el-radio>
                </el-radio-group>
            </div>
        </el-form>
        <template #footer>
            <div class="box-row">
                <el-button size="default" type="success" @click="ExtraSelect">补选...</el-button>
                <div style="flex:1"></div>
                <el-button size="default" type="primary" @click="onSure">保存</el-button>
                <el-button size="default" type="danger" @click="onCancel">取消</el-button>
            </div>
        </template>
        <div v-loading="loading" :class="{'ui-dlg-loading':true, 'ui-dlg-loading-show': loading}" :element-loading-text="'请稍后...'"></div>
    </el-dialog>
</template>
<script>
import { reactive, computed, toRefs } from 'vue-demi';
import { Delete } from '@element-plus/icons-vue';
import { useSocket } from '../../uiframe/services/socket';
import { UiShowDialog } from '../../uiframe/layout/components/CompFactory.vue';
import ExtraSelectDialog from './ExtraSelectDialog.vue'
import { dict } from '../../uiframe/utils';
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
    components:{
        Delete
    },
    props:{
        q:Object,
        done: Function,
        payload:Object,
        stores:Array,
        storeId:Number,
        mh:Number,
        isIn:Boolean
    },
    setup:(props)=>{
        let changed = false;
        const onmessage = (msg)=>ElMessage({message:msg.message, type:msg.success?'success':'error'}),
        isIn = props.isIn, storeId = props.storeId, curStore = props.stores.find(v=>storeId==v.id), data = reactive({
            dialogVisible: true,
            isIn,
            dialogTitle: isIn?`进货到 "${curStore.name}"`:`从"${curStore.name}"出货`,
            dialog: null,
            elForm: null,
            loading: false,
            filteredData: computed(()=>{
                return data.data.data.filter(v=>{
                    return !data.params.code || data.params.code.length==0 || v.name.indexOf(data.params.code)>=0 || v.code.indexOf(data.params.code)>=0;
                });
            }),
            data:{
                calc_mode: 0,
                realpay: null,
                store_id: storeId,
                settle_mode: 2,
                data: [],
                amount: computed(()=>{
                    var amount = 0;
                    data.data.data.forEach(row=>{
                        amount += (data.data.calc_mode==0 ? row.pack_price : row.piece_price) * row.op_num;
                    })
                    return amount;
                }),
            },
            params: {
                code:''
            },
            h: computed(()=>{
                return props.mh - 322;
            }),
            rules:{
                realpay:computed(()=>{
                    if(data.data.settle_mode > 0)
                        return [
                            {required: ()=>data.data.settle_mode > 0,message:'该项必填.'}
                        ];
                    return [];
                })
            }
        }),
        renewSelected = ()=>{
            useSocket().then(socket=>socket.rpc('sel.get',{store_id:storeId,with_goods:true}).then(res=>{
                let dc =dict(data.data.data, 'id'), dc1 = dict(res.data, 'id'), del = [];
                // 增加新的
                res.data.forEach(v=>{
                    if(!dc[v.id]){
                        v.op_num = 0;
                        data.data.data.push(v);
                        changed = true;
                    }
                })
                // 删除取消了的
                data.data.data.forEach(v=>{
                    if(!dc1[v.id]){
                        del.push(v.id);
                        changed = true;
                    }
                })
                del.forEach(v=>data.data.data.splice(data.data.data.findIndex(v1=>v1.id==v),1))
            }).catch(res=>{

            }))
        },
        methods = {
            
            onSure:()=>{
                data.elForm.validate().then(pass=>{
                    useSocket().then(socket=>{
                        let d=data.data, payload = {
                            store_id: storeId,
                            calc_mode: d.calc_mode,
                            settle_mode: d.settle_mode,
                            realpay: d.realpay,
                            in: isIn,
                            amount: d.amount,
                            goods: d.data.filter(v=>v.op_num>0).map(v=>{
                                return d.calc_mode == 1? {
                                    id: v.id,
                                    num: v.op_num,
                                    piece_price: v.piece_price
                                }:{
                                    id: v.id,
                                    num: v.op_num,
                                    pack_size: v.pack_size,
                                    pack_price: v.pack_price,
                                }
                            })
                        }

                        if(payload.goods.length == 0){
                            onmessage({success:false, message:'没有选择任何商品'});
                            return;
                        }

                        socket.rpc('purchase', payload).then(res=>{
                            onmessage(res);
                            changed = true;
                            data.dialogVisible = false;
                        }).catch(res=>{
                            onmessage(res);
                            console.log('catch:', res)
                        })
                    })
                }).catch(res=>{})
            },
            onCancel:()=>{
                data.dialogVisible = false;
            },
            init:()=>{
            },
            beforeClose:(next)=>{
                next();
            },
            finalThings:()=>{
                changed && props.q.resolve(true);
                props.done()
            },
            onSearch:(item)=>{

            },
            onRemoveItem:(item)=>{
                ElMessageBox.confirm(`确定要删除"${item.name}"吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    useSocket().then(socket=>socket.rpc('rmsel',{store_id:storeId,goods_id:item.id})).then(res=>{
                        changed = true;
                        data.data.data.splice(data.data.data.indexOf(item),1);
                    }).catch(() => {});
                }).catch(() => {
                });
            },
            ExtraSelect:()=>{
                UiShowDialog(ExtraSelectDialog, {storeId, mh:data.h, isRack:curStore.prop==1,stores:props.stores}).then(res=>{
                    renewSelected();
                }).catch(res=>{
                    renewSelected();
                })
            },
            filter:(v,r,c)=>{
                console.log('filter:', v,r,c)
            }
        };
        useSocket().then(socket=>socket.rpc('sel.get',{store_id:storeId,with_goods:true}).then(res=>{
            res.data.forEach(v=>{v.op_num=0;})
            data.data.data = res.data;
        }).catch(res=>{

        }))
        return {
            ...toRefs(data),
            ...methods,
        }
    }
}
</script>
<style lang="scss">
.ui-inout-dlg{
    width:60rem;max-width: 60rem;
    .el-dialog__body{
        padding: .5rem 1rem;
        .price-label{
            line-height: 2rem;
        }
        .op-num-ipt{
            max-width: 6rem;
            .el-input__wrapper{padding-left:20px;padding-right:20px;}
            .el-input-number__decrease,.el-input-number__increase{
                width:20px;
            }
        }
    }
}
</style>